package se.topshelf.golftracker.web.controller.hole;

import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import se.topshelf.golftracker.core.domain.Course;
import se.topshelf.golftracker.core.domain.Hole;
import se.topshelf.golftracker.core.service.BaseService;
import se.topshelf.golftracker.core.service.CourseService;
import se.topshelf.golftracker.web.validator.BaseEntityValidator;

import java.text.MessageFormat;

/**
 *  Validates Hole entities, so that they are ok save.
 */
public class HoleValidator extends BaseEntityValidator<Hole> {
    public static final String COURSE_FIELD_NAME = "course";
    public static final String SLOPE_INDEX_FIELD_NAME = "slopeIndex";
    public static final String ORDER_ON_COURSE_FIELD_NAME = "orderOnCourse";
    public static final String PAR_FIELD_NAME = "par";
    private CourseService courseService;


    public HoleValidator(CourseService courseService) {
        super(Hole.class);
        this.courseService = courseService;
    }


    @Override
    protected void validateFields(Hole entityToCheck, Errors errors) {
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, ORDER_ON_COURSE_FIELD_NAME, REQUIRED_ERROR_CODE, REQUIRED_ERROR_DEFAULT_MESSAGE);
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, SLOPE_INDEX_FIELD_NAME, REQUIRED_ERROR_CODE, REQUIRED_ERROR_DEFAULT_MESSAGE);
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, PAR_FIELD_NAME, REQUIRED_ERROR_CODE, REQUIRED_ERROR_DEFAULT_MESSAGE);
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, COURSE_FIELD_NAME, REQUIRED_ERROR_CODE, REQUIRED_ERROR_DEFAULT_MESSAGE);
    }

    @Override
    protected BaseService getBaseService() {
        return courseService;
    }

    @Override
    protected boolean isNaturalKeyEqual(Hole savedEntity, Hole entityToCheck) {
        return (savedEntity.getOrderOnCourse().equals(entityToCheck.getOrderOnCourse()) &&
                        savedEntity.getCourse().equals(entityToCheck.getCourse()));
    }

    @Override
    protected void doRejectOfNaturalField(Errors errors, Hole entityToCheck) {
        errors.rejectValue(ORDER_ON_COURSE_FIELD_NAME, "duplicate",
                MessageFormat.format("Duplicate Hole",
                        entityToCheck.getOrderOnCourse()));
    }
}
